package cn.codeinn.generator.service.impl;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import cn.codeinn.generator.entity.Table;
import cn.codeinn.generator.mapper.GeneratorMapper;
import cn.codeinn.generator.service.IGeneratorService;
import cn.codeinn.generator.util.GenCodeUtil;

@Service("generatorService")
@Configuration
@PropertySource(value = "classpath:generator.properties")
public class GeneratorServiceImpl implements IGeneratorService {

	@Autowired
	private GeneratorMapper generatorMapper;

	@Value("${package}")
	private String packageName;

	public Map<String, String> queryTable(String tableName) {
		return generatorMapper.queryTable(tableName);
	}

	public List<Map<String, String>> queryColumns(String tableName) {
		return generatorMapper.queryColumns(tableName);
	}

	@Override
	public byte[] generatorCode(Table table, String modelname) {
		table.setPackageName(packageName);
		table.setModuleName(modelname);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			String tableName = table.getTables().get(0);
			Map<String, String> tempTable = queryTable(tableName);
			List<Map<String, String>> columns = queryColumns(tableName);
			GenCodeUtil.businessProcess(tempTable, columns, table);
		} catch (Exception e) {
		}
		return outputStream.toByteArray();
	}

}
